import { store } from "@/store";
import { defineStore } from "pinia";
import ExpressCompanyAPI, {
  type ExpressCompanyListQuery,
  type ExpressCompanyType,
  type ExpressCompanyForm,
} from "@/api/logistics/company";

export const useExpressCompanyStore = defineStore("express-company", () => {
  const list = ref<ExpressCompanyType[]>([]);
  const totalCount = ref(0);
  const totalPage = ref(0);
  const loading = reactive({
    list: false,
    create: false,
    update: false,
    delete: false,
  });

  async function fetchList(params: ExpressCompanyListQuery) {
    loading.list = true;
    const response = await ExpressCompanyAPI.getExpressCompanyList(params);
    loading.list = false;
    if (response) {
      list.value = response.records;
      totalCount.value = response.total_count;
      totalPage.value = response.total_page;
    }
  }

  async function fetchCreate(data: Partial<ExpressCompanyForm>) {
    loading.create = true;
    try {
      await ExpressCompanyAPI.createExpressCompany(data);
      loading.create = false;
    } catch (error) {
      console.error("Error creating express company:", error);
      loading.create = false;
    }
  }

  async function fetchUpdate(data: Partial<ExpressCompanyForm>) {
    loading.update = true;
    try {
      await ExpressCompanyAPI.updateExpressCompany(data);
      loading.update = false;
    } catch (error) {
      console.error("Error updating express company:", error);
      loading.update = false;
    }
  }

  async function fetchDelete(id: number) {
    loading.delete = true;
    await ExpressCompanyAPI.deleteExpressCompany(id);
    loading.delete = false;
  }

  return {
    list,
    totalCount,
    totalPage,
    loading,
    fetchList,
    fetchCreate,
    fetchUpdate,
    fetchDelete,
  };
});

export const useExpressCompanyStoreHook = () => {
  return useExpressCompanyStore(store);
};
